package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.hmdp.utils.RedisConstants;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 查询所有商铺类型
     *
     * @return 商铺类型列表
     */
    public Result queryList() {
        // 1.查询redis
        String key = RedisConstants.CACHE_SHOP_TYPE_KEY;
        List<String> shopTypeListStr = stringRedisTemplate.opsForList().range(key, 0, -1);
        // 2.缓存命中
        if(shopTypeListStr != null && !shopTypeListStr.isEmpty()) {
            List<ShopType> shopTypeList = shopTypeListStr.stream().map(s -> JSONUtil.toBean(s, ShopType.class)).collect(Collectors.toList());
            return Result.ok(shopTypeList);
        }
        // 3.缓存未命中，查询数据库
        List<ShopType> shopTypeList = query().orderByAsc("sort").list();
        // 4.商铺类型为空
        if(shopTypeList == null || shopTypeList.isEmpty())
            return Result.fail("未查询到商铺类型");
        // 5.商铺类型不为空，写入到redis
        List<String> shopTypeStrs = shopTypeList.stream().map(JSONUtil::toJsonStr).collect(Collectors.toList());
        stringRedisTemplate.opsForList().rightPushAll(key, shopTypeStrs);
        stringRedisTemplate.expire(key, RedisConstants.CACHE_SHOP_TYPE_TTL, TimeUnit.DAYS);
        // 6.返回结果
        return Result.ok(shopTypeList);
    }
}
